package com.itheima.aop;

import com.itheima.domain.LoginInfo;
import com.itheima.domain.Result;
import com.itheima.domain.pojo.EmpLoginLog;
import com.itheima.mapper.EmpLoginLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;

@Component
@Aspect// 切面类
@Slf4j
public class EmpLoginLogAspect {

    @Autowired
    private EmpLoginLogMapper empLoginLogMapper;

    @Around("execution(* com.itheima.controller.LoginController.login(..))")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {

        //获取开始时间
        long start = System.currentTimeMillis();

        Object result = null;
        try {
            //调用目标方法
            result = pjp.proceed();
        } finally {
            //记录登录日志
            EmpLoginLog loginLog = new EmpLoginLog();
            loginLog.setLoginTime(LocalDateTime.now()); //登录时间
            long end = System.currentTimeMillis();
            loginLog.setCostTime(end - start); //登录耗时, 单位:ms

            //获取用户传入的参数
            Object[] args = pjp.getArgs();
            if (args != null && args.length > 0) {
                Map<String, Object> loginInfoMap = (Map<String, Object>) args[0];
                loginLog.setUsername((String) loginInfoMap.get("username"));
                loginLog.setPassword((String) loginInfoMap.get("password"));
            }

            //获取登录结果
            if (result != null) {
                Result re = (Result) result;
                loginLog.setIsSuccess(re.getCode().shortValue());
                if (re.getCode() == 1) {
                    LoginInfo loginInfo = (LoginInfo) re.getData();
                    loginLog.setJwt(loginInfo.getToken());
                }
            }
            empLoginLogMapper.insert(loginLog);
        }

        return result;
    }
}
